// 共享 API 客户端封装

// API 基础地址配置
export const API_BASE_URL = 'http://localhost:3000';

// API 响应类型
export interface ApiResponse<T = unknown> {
  code: number;
  message: string;
  data?: T;
}

// 用户信息类型
export interface UserInfo {
  id: string;
  username: string;
  email: string;
  role: string;
}

// 登录响应类型
export interface LoginResponse {
  token: string;
  user: UserInfo;
}

/**
 * 通用请求封装
 */
async function request<T>(
  url: string,
  options: RequestInit = {}
): Promise<ApiResponse<T>> {
  const token = localStorage.getItem('token');
  
  const headers: Record<string, string> = {
    'Content-Type': 'application/json',
  };

  // 如果有 token，自动添加到请求头
  if (token) {
    headers['Authorization'] = `Bearer ${token}`;
  }

  const response = await fetch(`${API_BASE_URL}${url}`, {
    ...options,
    headers,
  });

  const data = await response.json();
  return data;
}

/**
 * GET 请求
 */
export async function apiGet<T>(url: string): Promise<ApiResponse<T>> {
  return request<T>(url, { method: 'GET' });
}

/**
 * POST 请求
 */
export async function apiPost<T>(
  url: string,
  body?: unknown
): Promise<ApiResponse<T>> {
  return request<T>(url, {
    method: 'POST',
    body: JSON.stringify(body),
  });
}

/**
 * PUT 请求
 */
export async function apiPut<T>(
  url: string,
  body?: unknown
): Promise<ApiResponse<T>> {
  return request<T>(url, {
    method: 'PUT',
    body: JSON.stringify(body),
  });
}

/**
 * DELETE 请求
 */
export async function apiDelete<T>(url: string): Promise<ApiResponse<T>> {
  return request<T>(url, { method: 'DELETE' });
}

// ==================== 具体业务 API ====================

/**
 * 用户登录
 */
export async function login(username: string, password: string) {
  return apiPost<LoginResponse>('/auth/login', { username, password });
}

/**
 * 用户注册
 */
export async function register(
  username: string,
  email: string,
  password: string,
  role?: string
) {
  return apiPost<LoginResponse>('/auth/register', {
    username,
    email,
    password,
    role,
  });
}

/**
 * 获取当前用户信息
 */
export async function getCurrentUser() {
  return apiGet<UserInfo>('/auth/me');
}
